package content;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import config.Config;
public class PageParser {
	private Document document = null;
	
	public void scanPage(String url) throws Exception{
		Config.createJSONConfig();
		URLValidator.validateUrl(url);
		this.getPageMarkup(url);
		this.scanPageWithPhantomJs(url);
	}
	
	private void getPageMarkup(String url) throws IOException{
		document = Jsoup.connect("http://google.com").get();
	}
	
	private void scanPageWithPhantomJs(String url) throws IOException, ParseException{
		
		Runtime runTime = Runtime.getRuntime();
    	Process process = runTime.exec(Config.getPhantomjspath() + " /Volumes/E_Drive/node/citi/hello.js " + Config.getJsonConfigFileName() + " " + url );
    	try {
    		System.out.println("Executing");
			process.waitFor();
			System.out.println("Finishing");
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	InputStream is = process.getInputStream();
    	InputStreamReader isr = new InputStreamReader(is);
    	BufferedReader br = new BufferedReader(isr);
    	String output = " ";
    	output = br.readLine();
    	parseJsonOutput(output);
    	
	}
	
	private void parseJsonOutput(String JsonOutput) throws ParseException{
		  JSONParser parser=new JSONParser();
		  Object obj=parser.parse(JsonOutput);
		  JSONObject unitsJson = (JSONObject) obj;
		  System.out.println("=======decode=======");
		  System.out.println(unitsJson.get("font"));
		  System.out.println(unitsJson.get("footerLinks"));
		  System.out.println(unitsJson.get("googleAnalytics"));
		  System.out.println(unitsJson.get("socialMediaLinks"));
		   

	}
	
}
